package cn.edu.zut.soft.student.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author ChrisPhantom
 * @CreatDate 2021/02/25 10:37
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("LoginUser") != null) {
            return true;
        }
        response.sendRedirect("/");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null && !"redirect:/".equals(modelAndView.getViewName()) && !"error".equals(modelAndView.getViewName())) {
            String path = modelAndView.getViewName().split("/")[1];
            HttpSession session = request.getSession();
            String classify = (String) session.getAttribute("classify");
            if (!path.equals(classify)) {
                response.sendRedirect("/" + classify);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
